package daybook.model;

import daybook.Resources;
import daybook.annotation.Bean;
import daybook.exception.ValidationException;
import org.immutables.value.Value;

@Bean
@Value.Immutable
public abstract class Commodity {
    public abstract String getName();
    public abstract boolean isCurrency();
    public abstract int getFractionDigitCount();

    @Value.Default
    public String getDescription() {
        return "";
    }

    public boolean similar(Commodity commodity) {
        return getName().equals(commodity.getName())
                && isCurrency() == commodity.isCurrency()
                && getFractionDigitCount() == commodity.getFractionDigitCount();
    }

    public static final Commodity CNY = ImmutableCommodity.builder()
            .name("CNY")
            .currency(true)
            .fractionDigitCount(2)
            .description("人民币")
            .build();

    public void validate() {
        // fractionDigitCount不得为负
        if (getFractionDigitCount() < 0) {
            throw ValidationException.of(Resources.ErrorMessages.NEGATIVE_COMMODITY_FRACTION_DIGIT_COUNT,
                    getName(), getFractionDigitCount());
        }

        if (!getName().chars().allMatch(ch -> Character.isLetter((char) ch))) {
            throw ValidationException.of(Resources.ErrorMessages.INVALID_COMMODITY_NAME, getName());
        }
    }
}
